package com.sunlgggg.view;


import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static com.sunlgggg.util.HttpRequestUtils.*;

public class Login extends JFrame implements ActionListener{

    public static String account;
    JButton login;
    JButton cancel;
    JTextField unameField;
    JPasswordField upsdField;
    static JDialog dialog = new JDialog();


    public Login() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        dialog.setSize(300, 300);
        dialog.setIconImage(new ImageIcon("resource/icon.jpg").getImage());
        dialog.setTitle("登录界面");
        JLabel unameLabel = new JLabel("账号：");
        JLabel upsdLabel = new JLabel("密码：");
        login = new JButton("登录");
        cancel = new JButton("取消");
        unameField = new JTextField();
        upsdField = new JPasswordField();
        this.setAlwaysOnTop(true);
        this.setVisible(false);

        unameLabel.setBounds(50, 50, 50, 30);
        unameField.setBounds(100, 50, 150, 30);
        upsdLabel.setBounds(50, 100, 50, 30);
        upsdField.setBounds(100, 100, 150, 30);
        login.setBounds(60, 160, 60, 40);

        login.addActionListener(this);

        cancel.setBounds(160, 160, 60, 40);

        cancel.addActionListener(e -> System.exit(0));

        dialog.setLayout(null);
        dialog.add(login);
        dialog.add(cancel);
        dialog.add(unameField);
        dialog.add(unameLabel);
        dialog.add(upsdLabel);
        dialog.add(upsdField);
        dialog.setLocationRelativeTo(null);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    }


    /**
     * Invoked when an action occurs.
     *
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        String ret = post("user/login", "account=" + unameField.getText() + "&password=" + upsdField.getText());
        if (ret.equals("success")) {
            this.account = unameField.getText();
            new MainFrame(account);
            this.dispose();
            dialog.setVisible(false);
            this.setVisible(false);

        } else {
            JOptionPane.showConfirmDialog(null, "登录错误", "", JOptionPane.CLOSED_OPTION);
        }
    }

    public static void main(String[] args) {
        new Login();
    }
}

